﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace GmailChecker.Utils
{
    static class MailBox
    {        
        public static string Email { get; set; }
        public static string Password { get; set; }
        public static string CheckPeriod { get; set; }

        private static DateTime _lastCheck = DateTime.MinValue;
        private static DateTime _lastUnreadMailDate = DateTime.MinValue;

        private static List<Mail> GetNew()
        {
            List<Mail> mails = new List<Mail>();

            WebRequest request = WebRequest.Create(@"https://mail.google.com/mail/feed/atom");
            request.PreAuthenticate = true;
            
            NetworkCredential credential = new NetworkCredential(Email, Password);            
            request.Credentials = credential;

            using (WebResponse response = request.GetResponse())
            {
                Stream stream = response.GetResponseStream();                
                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                {
                    XmlDocument newMailsXml = new XmlDocument();
                    newMailsXml.LoadXml(reader.ReadToEnd());

                    XmlNodeList unreadMailEntries = newMailsXml.GetElementsByTagName("entry");
                    foreach (XmlNode mailEntry in unreadMailEntries)
                    {
                        mails.Add(new Mail()
                            {                                
                                From =
                                    mailEntry["author"]["name"].InnerText + " <" +
                                    mailEntry["author"]["email"].InnerText + ">",
                                MailModify = DateTime.Parse(mailEntry["modified"].InnerText)
                            });
                    }
                }                
            }

            return mails;
        }

        public static void Check()
        {
            try
            {   
                int newUnreadMails = 0;
                List<string> from = new List<string>();

                List<Mail> mails = GetNew();
                foreach (Mail mail in mails)
                {
                    if (mail.MailModify > _lastCheck)
                    {
                        newUnreadMails++;            
                    
                        if (!from.Contains(mail.From))
                        {
                            from.Add((mail.From));
                        }                                
                    }
                    if (mail.MailModify > _lastUnreadMailDate)
                        _lastUnreadMailDate = mail.MailModify;
                }

                _lastCheck = _lastUnreadMailDate;

                if (newUnreadMails > 0)
                {
                    App.WaitDialogResult = true;

                    string msgTitle;
                    string msgBody;

                    if (newUnreadMails == 1)
                    {
                        msgTitle = "New Mail";
                        msgBody = "Mail from " + from[0];                        
                    }
                    else
                    {
                        msgTitle = "New Mails";

                        if (from.Count == 1)
                        {
                            msgBody = "Mails from " + from[0];                                                       
                        }
                        else
                        {
                            msgBody = "Mails from: " + string.Join(Environment.NewLine + new string(' ', 21), from);
                        }                        
                    }

                    MessageBox.Show(msgBody, msgTitle, MessageBoxButtons.OK, MessageBoxIcon.Information);                    
                    App.WaitDialogResult = false;
                }                
            }
            catch
            {                
            }
        }
    }
}
